package com.xinhe.web.exception;

import com.xinhe.web.common.BusinessException;
import com.xinhe.web.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author zhanghou
 * @version 1.0
 * @title: ExceptionAdviceHandler
 * @description: 异常前置处理器
 * @date 2024/1/26 17:13
 */
@RestControllerAdvice
@Slf4j
public class ExceptionAdviceHandler {

    public Result handBusinessException(BusinessException ex){
        log.info("========自定义异常========");
        return Result.failed(ex.getErrorCode(),ex.getMessage());
    }
    public Result exception(Exception ex) {
        log.error("========系统异常========，异常的错误为{}",ex);
        return Result.failed(500,ex.getMessage());
    }
    public Result handlerMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        log.error("========方法参数异常========，异常的错误为{}",ex);
        return Result.failed(1100,"方法参数不正常");
    }
    @ExceptionHandler(value = Exception.class)
    public Result dealWithException(Exception e) {
        if(e instanceof MethodArgumentNotValidException){
            return handlerMethodArgumentNotValidException((MethodArgumentNotValidException)e);
        }else if (e instanceof BusinessException) {
            return handBusinessException((BusinessException) e);
        }else if (e instanceof RuntimeException) {
            return exception(e);
        } else {
            return Result.failed(9999,"未知异常");
        }
    }


}